package com.zh.juc.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Author: zhanghuan
 * @date: 2022/10/7 15:07
 * @description: create it
 *
 * 获取结果和出发计算
 */
public class CompletableFutureAPI1Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "ok";
        });
        // 不见不散
       // System.out.println(completableFuture.get());
       //  过时不侯
       // System.out.println(completableFuture.get(2L, TimeUnit.SECONDS));
       //  join不报异常，功能与get相同
       // System.out.println(completableFuture.join());

        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 立即获取结果不阻塞，计算完，返回计算结果；没计算完，返回设置的结果
       // System.out.println(completableFuture.getNow("xxx"));

        // 是否打断get方法，立即返回括号值
        System.out.println(completableFuture.complete("completeValue") + "\t" + completableFuture.join());

    }
}
